package com.facebook.android;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.UUID;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class MyCache {
	private final String NAME_CACHE; 
	Hashtable<String, String> _filenames;
	
	@SuppressWarnings(value = {"unchecked"})
	public MyCache(Context context) {
		NAME_CACHE = "pic_cache5";
		try {
			ObjectInputStream is = new ObjectInputStream(context.openFileInput(NAME_CACHE));
			_filenames = (Hashtable<String, String>)is.readObject();
			is.close();
		} catch(Exception e) {
			Log.d("cache", "can't find the cache file" + e.toString());
		}
		
		if(_filenames == null) {
			_filenames = new Hashtable<String, String>();
			Log.d("cache", "create a new cache");
		}
	}
	
	public void save(Context context) {
		try {
			ObjectOutputStream os = new ObjectOutputStream(context.openFileOutput(NAME_CACHE, Context.MODE_PRIVATE));
			os.writeObject(_filenames);
			os.close();
		} catch(Exception e) {
			Log.d("cache", "write file error");
		}
	}

	public Drawable getImage(URL url, Context context) {
		Log.d("cache", "start to get image" + url);
		
		if(_filenames == null) {
			Log.d("cache", "cache is null");
			return null;
		}

		if(!_filenames.containsKey(url.toString())) {
			try {
				String uuid;
				do {
					uuid = UUID.randomUUID().toString() + ".png";
				} while (_filenames.contains(uuid));
				_filenames.put(url.toString(), uuid);
				
				// get the image
				InputStream is;
				OutputStream os = null;
				Bitmap b = null;
				for(int i = 0; i < 100; i ++) {
					is = (InputStream)url.getContent();
					os = context.openFileOutput(uuid, Context.MODE_PRIVATE);
					Log.d("cache", (is == null)?"is is null":"is ok");
					Log.d("cache", (os == null)?"os is null":"os ok");
					b = BitmapFactory.decodeStream(is);
					if(b != null)
						break;
				}
				b.compress(CompressFormat.PNG, 100, os);
				Log.d("cache", "finally got image" + url);
			} catch (Exception e) {
				Log.d("cache", "some error: " + e);
			}
			Log.d("cache", "put in cache: " + url);
		} else
			Log.d("cache", "it's in the cache: " + url);

		try {
			Log.d("cache", "start getting image from cache");
			//InputStream is = (InputStream)url.getContent();
			Drawable d = Drawable.createFromStream(context.openFileInput(_filenames.get(url.toString())), url.toString());

			Log.d("cache", (d == null)?"image ok":"no image" + url);
			
			return d;
		} catch (Exception e) {
			Log.d("cache", "get image error: " + url + " - " + e);
			return null;
		}
	}
}
